package cn.chengpengper.rpc.serialization.protostuff;

import cn.chengpengper.rpc.common.exception.SerializerException;
import cn.chengpengper.rpc.serialization.api.Serialization;
import cn.chengpengper.rpc.spi.annotation.SpiClass;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import lombok.extern.slf4j.Slf4j;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chengpeng.hu
 */
@Slf4j
@SpiClass
public class ProtostuffSerialization implements Serialization {

    private Objenesis objenesis = new ObjenesisStd();

    private Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    private <T> Schema<T> getSchema(final Class<T> clazz) {
        Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
        if (Objects.isNull(schema)) {
            schema = RuntimeSchema.createFrom(clazz);
            if (Objects.nonNull(schema)) {
                cachedSchema.put(clazz, schema);
            }
        }
        return schema;
    }

    @Override
    public <T> byte[] serialize(T obj) {
        log.info("execute protostuff serialize");
        if (Objects.isNull(obj)) {
            throw new SerializerException("serialize object is null");
        }
        Class<T> cls = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            final Schema<T> schema = getSchema(cls);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } finally {
            buffer.clear();
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        log.info("execute protostuff deserialize");
        if (Objects.isNull(data)) {
            throw new SerializerException("deserialize data is null");
        }
        try {
            T message = (T) objenesis.newInstance(clazz);
            Schema<T> schema = getSchema(clazz);
            ProtostuffIOUtil.mergeFrom(data, message, schema);
            return message;
        } catch (Exception e) {
            throw new SerializerException(e.getMessage(), e);
        }
    }
}
